package main

import (
	"fmt"
	goredislib "github.com/go-redis/redis/v8"
	"github.com/go-redsync/redsync/v4"
	"github.com/go-redsync/redsync/v4/redis/goredis/v8"
	"time"
)

func main() {
	client := goredislib.NewClient(&goredislib.Options{
		Addr:     "111.229.176.202:6379",
		Password: "www#1234",
		DB:       2,
	})

	pool := goredis.NewPool(client)

	rs := redsync.New(pool)

	mutexname := "my-global-mutex"
	mutex := rs.NewMutex(mutexname, redsync.WithExpiry(10*time.Second))

	if err := mutex.Lock(); err != nil {
		panic(err)
	}
	fmt.Println("lock success.")
	//创建一个channel，用来通知续租goroutine任务已经完成
	done := make(chan bool)

	// 开启一个goroutine，周期性地续租锁
	go func() {
		ticker := time.NewTicker(3 * time.Second) // 按照需求调整
		defer ticker.Stop()

		for {
			select {
			case <-ticker.C:
				ok, err := mutex.Extend()
				if err != nil {
					fmt.Println("Failed to extend lock:", err)
				} else if !ok {
					fmt.Println("Failed to extend lock: not successes")
				} else {
					fmt.Println("extend lock successes")
				}
			case <-done:
				return
			}
		}
	}()

	// 执行需要锁的工作
	time.Sleep(30 * time.Second)
	//通知goRoutine停止续租
	close(done)

	if ok, err := mutex.Unlock(); !ok || err != nil {
		panic("unlock failed")
	}
}
